<template>
  <div class="modal-overlay" @click.self="$emit('close')">
    <div class="modal-content">
      <div class="modal-header">
        <h3>事件详情</h3>
        <button class="close-btn" @click="$emit('close')">×</button>
      </div>
      <div class="modal-body">
        <div class="detail-grid">
          <div class="detail-item">
            <span class="label">类型:</span>
            <span class="value">{{ incident.incidentType }}</span>
          </div>
          <div class="detail-item">
            <span class="label">位置:</span>
            <span class="value">{{ locationDisplay }}</span>
          </div>
          <div class="detail-item">
            <span class="label">报告时间:</span>
            <span class="value">{{ formatDateTime(incident.reportTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">完成时间:</span> <!-- 新增完成时间 -->
            <span class="value">{{ formatDateTime(incident.completeTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">处理警员:</span> <!-- 新增处理警员 -->
            <span class="value">{{ incident.officerName || '未指派' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">状态:</span>
            <span :class="['status-badge', getStatusClass(incident.incidentStatus)]">{{ getStatusDisplay(incident.incidentStatus) }}</span>
          </div>
          <div class="detail-item full-width">
            <span class="label">处理详情:</span> <!-- 新增处理详情 -->
            <span class="value handling-details">{{ incident.handlingDetails || '暂无处理详情' }}</span>
          </div>
          <div class="detail-item full-width">
            <span class="label">描述:</span>
            <span class="value description">{{ incident.description }}</span>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" @click="$emit('close')">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import axios from 'axios';

// 状态枚举映射（枚举名称到中文描述）
const statusMap = {
  'UNPROCESSED': '未处理',
  'PROCESSING': '处理中',
  'COMPLETED': '已完成'
};

// 状态到CSS类名的映射
const statusClassMap = {
  'UNPROCESSED': 'status-pending',
  'PROCESSING': 'status-processing',
  'COMPLETED': 'status-resolved'
};

const props = defineProps<{
  incident: any;
}>();

// 高德地图API配置
const AMAP_API_KEY = 'e67f0e9520643f148baa0e9747a27038';

// 位置加载状态
const isLocationLoading = ref(false);
const locationAddress = ref<string | null>(null);

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取状态显示文本
const getStatusDisplay = (status: string) => {
  return statusMap[status as keyof typeof statusMap] || status;
};

// 获取状态对应的CSS类名
const getStatusClass = (status: string) => {
  return statusClassMap[status as keyof typeof statusClassMap] || 'status-unknown';
};

// 获取地址信息的函数
const getAddressByCoordinates = async (lng: number, lat: number) => {
  try {
    const response = await axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_API_KEY}&location=${lng},${lat}`);
    if (response.data.status === '1') {
      return response.data.regeocode.formatted_address;
    }
    return null;
  } catch (error) {
    console.error('获取地址信息失败:', error);
    return null;
  }
};

// 处理位置显示
const locationDisplay = computed(() => {
  if (isLocationLoading.value) return '位置加载中...';

  // 如果有地址信息，直接返回
  if (locationAddress.value) {
    return locationAddress.value;
  }

  // 如果有经纬度，显示经纬度
  if (props.incident.coordinates && props.incident.coordinates.length >= 2) {
    const lng = parseFloat(props.incident.coordinates[0].toString()).toFixed(6);
    const lat = parseFloat(props.incident.coordinates[1].toString()).toFixed(6);
    return `经度: ${lng}, 纬度: ${lat}`;
  }

  // 否则显示位置未知
  return '位置未知';
});

// 加载位置信息
const loadLocationInfo = async () => {
  if (!props.incident.coordinates || props.incident.coordinates.length < 2) {
    return;
  }

  isLocationLoading.value = true;

  try {
    const lng = parseFloat(props.incident.coordinates[0].toString());
    const lat = parseFloat(props.incident.coordinates[1].toString());

    const address = await getAddressByCoordinates(lng, lat);
    if (address) {
      locationAddress.value = address;
    }
  } catch (error) {
    console.error('获取地址信息失败:', error);
  } finally {
    isLocationLoading.value = false;
  }
};

// 当事件数据变化时重新加载位置信息
onMounted(() => {
  loadLocationInfo();
});
</script>

<style scoped>
@import "@/assets/styles/views/dashboard/IncidentDetailModal.css";
</style>
